#ifndef CORE_GLASS_H
#define CORE_GLASS_H
#include "Material.h"
#include "Hitable.h"
namespace RayTracer
{
	class Glass : public Material 
	{
	public:
		Glass(float index_of_refraction) : ir(index_of_refraction) {}

		virtual bool Scatter(const Ray& r_in, const HitRecord& rec, 
			vec3& attenuation, Ray& scattered) const override 
		{
			attenuation = vec3(1.0, 1.0, 1.0);
			float refraction_ratio = rec.front_face ? (1.0f / ir) : ir;

			vec3 unit_direction = glm::normalize(r_in.direction());
			float cos_theta = fmin(dot(-unit_direction, rec.normal), 1.0);
			float sin_theta = sqrt(1.0 - cos_theta * cos_theta);

			bool cannot_refract = refraction_ratio * sin_theta > 1.0;
			vec3 direction;

			if (cannot_refract || (reflectance(cos_theta, refraction_ratio) > Random01()))
				direction = reflect(unit_direction, rec.normal);
			else
				direction = refract(unit_direction, rec.normal, refraction_ratio);

			scattered = Ray(rec.position, direction);
			return true;
		}
	private:
		static float reflectance(float cosine, float ref_idx) 
		{
			auto r0 = (1 - ref_idx) / (1 + ref_idx);
			r0 = r0 * r0;
			return r0 + (1 - r0)*pow((1 - cosine), 5);
		}
	public:
		float ir; // Refraction
	};
}
#endif // !CORE_GLASS_H
